package com.Test.com;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Client {

    static HashMap<String, String> friendMap = new HashMap<>();
    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner sc=new Scanner(System.in);
        while (true){
            client();
            System.out.println("是否继续?[Y/N]");
            String s = sc.nextLine();
            if (s.equals("N")) {
                break;
            }
        }
    }

    public static void client() throws IOException, InterruptedException {
        ArrayList<Boolean>threadState=new ArrayList<Boolean>();
        threadState.add(true);
        Scanner sc = new Scanner(System.in);
        DatagramSocket serveMachineIpdatagramSocket=new DatagramSocket(5050);
        byte[]bys=new byte[1024];
        DatagramPacket serveMachineIpdatagramPacket=new DatagramPacket(bys,bys.length);
        System.out.println("等待服务器响应...");
        serveMachineIpdatagramSocket.receive(serveMachineIpdatagramPacket);
        String serveMachineIp = new String(bys, 0, bys.length);
        Socket socket = new Socket(serveMachineIp, 8000);
        printFriendMap();
        System.out.println("请选择好友聊天");
        String receiveUserName = sc.next();
        String receiveIp = friendMap.get(receiveUserName);
        ClientSendRunnable clientSendRunnable = new ClientSendRunnable(socket, receiveUserName, receiveIp,threadState);
        ClientReceiveRunnable clientReceiveRunnable = new ClientReceiveRunnable(socket, friendMap,threadState);
        System.out.println("开始聊天!");
        creatChat(clientSendRunnable, clientReceiveRunnable);
    }


    public static void creatChat(ClientSendRunnable clientSendRunnable, ClientReceiveRunnable clientReceiveRunnable) throws InterruptedException {
        Thread clientSendThread = new Thread(clientSendRunnable);
        clientSendThread.start();
        Thread clientReceiveThread = new Thread(clientReceiveRunnable);
         clientReceiveThread.start();
         clientSendThread.join();
         clientReceiveThread.join();
    }

    public static void printFriendMap() {
        friendMap.put("ewew", "192.168.13.45");
        friendMap.put("eatr", "192.168.13.45");
        friendMap.put("uiik", "192.168.13.45");
        friendMap.put("mfyf", "192.168.13.45");
        System.out.println("好友列表!");
        System.out.println("**********************************");
        System.out.println("用户名\t\t\tip");
        for (Map.Entry<String, String> entry : friendMap.entrySet()) {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }
        System.out.println("**********************************");
    }
}
